import { defineStore } from 'pinia'
import { login, register, getCurrentUser, sendRegisterCode, sendResetPasswordCode, resetPassword } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null,
    isAuthenticated: false
  }),

  actions: {
    // 初始化用户状态
    async init() {
      if (this.token) {
        try {
          const res = await getCurrentUser()
          this.user = res.data.user
          this.isAuthenticated = true
        } catch (error) {
          this.logout()
        }
      }
    },

    // 用户登录
    async login(credentials) {
      try {
        const res = await login(credentials)
        this.user = res.data.user
        this.token = res.data.token
        this.isAuthenticated = true
        localStorage.setItem('token', this.token)
        return res
      } catch (error) {
        throw error
      }
    },

    // 用户注册
    async register(userData) {
      try {
        const res = await register(userData)
        this.user = res.data.user
        this.token = res.data.token
        this.isAuthenticated = true
        localStorage.setItem('token', this.token)
        return res
      } catch (error) {
        throw error
      }
    },

    // 发送注册验证码
    async sendRegisterCode(email) {
      try {
        return await sendRegisterCode({ email })
      } catch (error) {
        throw error
      }
    },

    // 发送重置密码验证码
    async sendResetPasswordCode(email) {
      try {
        return await sendResetPasswordCode({ email })
      } catch (error) {
        throw error
      }
    },

    // 重置密码
    async resetPassword(data) {
      try {
        return await resetPassword(data)
      } catch (error) {
        throw error
      }
    },

    // 用户登出
    logout() {
      this.user = null
      this.token = null
      this.isAuthenticated = false
      localStorage.removeItem('token')
    },

    // 更新用户信息
    updateUser(user) {
      this.user = { ...this.user, ...user }
    }
  },

  getters: {
    // 获取当前用户
    currentUser: (state) => state.user,
    // 检查是否已登录
    isLoggedIn: (state) => state.isAuthenticated,
    // 检查是否是VIP用户
    isVIP: (state) => state.user?.role === 'vip',
    // 检查是否是管理员
    isAdmin: (state) => state.user?.role === 'admin'
  }
})